package com.blb.demo1;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Random;

/**
 * 客户端
 */
public class MyClient {

    static Random random = new Random();

    /**
     * 连接服务器
     *
     * @param ip   服务器的ip
     * @param port 服务器的端口
     */
    public void connect(String ip, int port, String message) {
        //创建socket对象，同时连接服务器

        try {
            Socket socket = new Socket(ip, port);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            System.out.println("客户端连接了服务器");
            objectOutputStream.writeUTF(message);
            objectOutputStream.flush();
            try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());) {
                String s = objectInputStream.readUTF();
                System.out.println(s);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) {
        while (true) {
            int i = random.nextInt(100000);

            new MyClient().connect("192.168.1.111", 8888, "" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

//        new MyClient().connect("192.168.1.100",8888,"aaa");
    }


}
